package com.gxa.eshop.admin.controller;


import com.gxa.eshop.core.exception.BusinessException;
import com.gxa.eshop.core.pojo.Goods;
import com.gxa.eshop.core.utils.JsonResult;
import com.gxa.eshop.admin.service.GoodsService;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {


    @Resource
    GoodsService goodsService;

    @Resource
    JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    JmsTemplate jmsTemplate;


    @PostMapping("/update")
    public JsonResult itemDetail(Goods goods) throws BusinessException, URISyntaxException {
        Integer lines = goodsService.updateById(goods);
        JsonResult jsonResult = new JsonResult();
        if (lines > 0) {
            jsonResult.setCode("1");
            jsonResult.setMsg("修改成功");
        } else {
            throw new BusinessException("修改失败,请检查商品编号是否真正确");
        }

//        给前台portal发送一个远程调用请求,根据id删除缓存
//        RestTemplate restTemplate = new RestTemplate();
//        URI uri = new URI("http://localhost:8080/goods/delete");
//        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
//        paramMap.add("id",goods.getId());
//        String result = restTemplate.postForObject(uri, paramMap, String.class);
//        System.out.println("result"+result);
        //把要删除的商品的缓存的id发送到消息队列上,存在一个叫goodCache 的队列
        jmsTemplate.convertAndSend("goodsCache",goods.getId());

        return jsonResult;
    }


    @PostMapping("/selectAll")
    public JsonResult selectAll() {
        List<Goods> goodslist = goodsService.selectAll();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(goodslist);
        return jsonResult;
    }
}
